package com.christina.engine.execution.impl;

import com.christina.engine.execution.AbstractServiceExecutor;
import com.christina.engine.execution.model.ExecutionRequest;
import com.christina.engine.execution.model.ExecutionResult;
import com.christina.service.domain.chat.ChatDomainService;
import com.christina.service.domain.chat.model.ChatRequest;
import com.christina.service.domain.chat.model.ChatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 聊天服务执行器
 * 负责执行聊天相关的业务逻辑
 * 
 * @author Christina
 */
@Slf4j
@Component
public class ChatServiceExecutor extends AbstractServiceExecutor {
    
    private final ChatDomainService chatDomainService;
    
    public ChatServiceExecutor(ChatDomainService chatDomainService) {
        super("ChatServiceExecutor", new String[]{"CHAT", "CONVERSATION"}, 100);
        this.chatDomainService = chatDomainService;
    }
    
    @Override
    protected ExecutionResult doExecute(ExecutionRequest request) {
        log.debug("Executing chat service for request: {}", request.getRequestId());
        
        try {
            // 验证参数
            validateChatParameters(request);
            
            // 构建聊天请求
            ChatRequest chatRequest = buildChatRequest(request);
            
            // 调用聊天领域服务
            ChatResponse chatResponse = chatDomainService.processChat(chatRequest);
            
            // 构建执行结果
            return ExecutionResult.success(Map.of(
                    "response", chatResponse.getContent(),
                    "conversationId", chatResponse.getConversationId(),
                    "messageId", chatResponse.getMessageId(),
                    "timestamp", chatResponse.getTimestamp()
            ), getName());
                    
        } catch (Exception e) {
            log.error("Error executing chat service", e);
            return ExecutionResult.failure("Failed to process chat request: " + e.getMessage(), e, getName());
        }
    }
    
    /**
     * 验证聊天参数
     * 
     * @param request 执行请求
     */
    private void validateChatParameters(ExecutionRequest request) {
        // 验证消息内容
        String message = request.getParameter("message", String.class);
        if (message == null || message.trim().isEmpty()) {
            throw new IllegalArgumentException("Message cannot be null or empty");
        }
        
        // 验证消息长度
        if (message.length() > 2000) {
            throw new IllegalArgumentException("Message too long, maximum 2000 characters allowed");
        }
        
        // 验证用户ID
        Long userId = request.getParameter("userId", Long.class);
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("Valid user ID is required");
        }
        
        // 设置默认值
        if (!request.hasParameter("chatType")) {
            request.addParameter("chatType", "general");
        }
        
        if (!request.hasParameter("language")) {
            request.addParameter("language", "zh-CN");
        }
        
        if (!request.hasParameter("sessionId")) {
            String sessionId = generateSessionId(request);
            request.addParameter("sessionId", sessionId);
        }
    }
    
    /**
     * 构建聊天请求
     * 
     * @param request 执行请求
     * @return 聊天请求
     */
    private ChatRequest buildChatRequest(ExecutionRequest request) {
        return ChatRequest.builder()
                .message(request.getParameter("message", String.class))
                .userId(request.getParameter("userId", Long.class))
                .sessionId(request.getParameter("sessionId", String.class))
                .requestTime(LocalDateTime.now())
                .build();
    }
    
    /**
     * 生成会话ID
     * 
     * @param request 执行请求
     * @return 会话ID
     */
    private String generateSessionId(ExecutionRequest request) {
        Long userId = request.getParameter("userId", Long.class);
        long timestamp = System.currentTimeMillis();
        return String.format("chat_%s_%d", userId, timestamp);
    }
}